package com.test.cordova.util;

/**
 * Created by chenrb on 2017/3/28.
 */

public class HexUtil {

    /**
     * 对字符串str进行16位补位（不足部分补位字符串GZZS，循环补位）
     *
     * @param str
     * @return
     */
    public static String strCovered16(String str) {
        if (str.length() < 16) {
            str += "GZZSGZZSGZZSGZZS";
        }
        if (str.length() > 16) {
            str = str.substring(0, 16);
        }
        return str;
    }


    /**
     * hex转byte数组
     *
     * @param hex
     * @return
     */
    public static byte[] hexToBytes(String hex) {
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte) intVal);
        }
        return ret;
    }

    /**
     * byte数组转hex
     *
     * @param src
     * @return
     */
    public static String bytesToHex(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


}
